package com.tcwlkj.uuService.ui;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.baidu.overlay.BikingRouteOverlay;
import com.tcwlkj.uuService.baidu.overlay.OverlayManager;
import com.tcwlkj.uuService.model.OrderModel;
import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.CommomDialog;
import com.tcwlkj.uuService.utils.Const;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/11/15 0015.
 */

public class NoOrderMapActivity extends BaseActivity implements BaiduMap.OnMapClickListener,
        OnGetRoutePlanResultListener {
    @Bind(R.id.map_view)
    MapView map_view;
    @Bind(R.id.tv_order_type)
    TextView tv_order_type;
    @Bind(R.id.tv_distance)
    TextView tv_distance;
    @Bind(R.id.tv_start_addr)
    TextView tv_start_addr;
    @Bind(R.id.tv_end_addr)
    TextView tv_end_addr;
    @Bind(R.id.bt_submit)
    Button bt_submit;
    @Bind(R.id.tv_MorKm)
    TextView tv_MorKm;
    @Bind(R.id.tv_money)
    TextView tv_money;
    @Bind(R.id.img_location)
    ImageView img_location;

    private OrderModel orderModel;
    /**
     * 地图实例
     */
    private BaiduMap mBaiduMap;
    int nodeIndex = -1; // 节点索引,供浏览节点时使用
    RouteLine route = null;
    OverlayManager routeOverlay = null;
    boolean useDefaultIcon = false;
    // 搜索相关
    RoutePlanSearch mSearch = null;

    LatLng lat_start, lat_end,lat_current;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_no_order_map);
        orderModel = (OrderModel) getIntent().getSerializableExtra("orderModel");
        ButterKnife.bind(this);
        initview();
        initBaiduMap();
    }
    private void initview() {
        changeTitle("订单地图");
        map_view.removeViewAt(1);
        lat_current=new LatLng(ChcheUtils.getInstance().getLocationModel().getLat(),ChcheUtils.getInstance().getLocationModel().getLng());
        if (Double.valueOf(orderModel.getDTakeDist()) < 1000) {
            tv_distance.setText(Math.ceil(Double.valueOf(orderModel.getDTakeDist())) + "");
            tv_MorKm.setText("米");
        } else {
            tv_distance.setText(new java.text.DecimalFormat("#.00").format(Double.valueOf(orderModel.getDTakeDist()) / 1000));
            tv_MorKm.setText("公里");
        }
        tv_money.setText("￥"+orderModel.getDriverFreightMoney());

        if(orderModel.getSendSubType().equals("301")){//就近买
            tv_start_addr.setText("就近买(不限制购买地址)");
        }else {
            tv_start_addr.setText(orderModel.getBegShowAddress());
        }
        switch (orderModel.getOrderType()){
            case "0"://实时
                break;
            case "1"://预约
                break;
            case "2"://指派
                break;
        }
        switch (orderModel.getSendType()){
            case "10"://送
                tv_order_type.setText("同城送");
                tv_end_addr.setText(orderModel.getEndShowAddress());
                break;
            case "20"://取
                tv_order_type.setText("同城取");
                tv_end_addr.setText(orderModel.getEndShowAddress());
                break;
            case "30"://买
                tv_order_type.setText("同城买");
                tv_end_addr.setText(orderModel.getEndShowAddress());
                break;
            case "40"://帮
                tv_order_type.setText("同城帮");
                if(orderModel.getHelpInfo().equals("")){
                    tv_end_addr.setText("暂无");
                }else {
                    tv_end_addr.setText(orderModel.getHelpInfo());
                }
                break;
            case "50"://排
                tv_order_type.setText("同城排");
                if(orderModel.getHelpInfo().equals("")){
                    tv_end_addr.setText("暂无");
                }else {
                    tv_end_addr.setText(orderModel.getHelpInfo());
                }
                break;
        }
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new CommomDialog(NoOrderMapActivity.this, R.style.dialog, "确定要抢单吗?", new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        Intent intent=new Intent();
                        intent.putExtra("orderId",orderModel.getID());
                        setResult(2,intent);
                        finish();
                    }
                }).show();
            }
        });
        img_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lat_current == null) {
                    return;
                } else {
                    MapStatus mMapStatus = new MapStatus.Builder()
                            .target(lat_current)
                            .zoom(18)
                            .build();
                    //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                    MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                    //改变地图状态
                    mBaiduMap.animateMapStatus(mMapStatusUpdate);
                }
            }
        });

    }

    private void initBaiduMap() {
        mBaiduMap = map_view.getMap();

//        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(13.0f);
//        mBaiduMap.animateMapStatus(msu);

        if(orderModel.getSendType().equals("10")||orderModel.getSendType().equals("20")||orderModel.getSendType().equals("30")){
            lat_start = new LatLng(Double.parseDouble(orderModel.getBegLocLat()), Double.parseDouble(orderModel.getBegLocLng()));
            lat_end = new LatLng(Double.parseDouble(orderModel.getEndLocLat()), Double.parseDouble(orderModel.getEndLocLng()));
        }else if(orderModel.getSendType().equals("40")||orderModel.getSendType().equals("50")){
            lat_start = new LatLng(ChcheUtils.getInstance().getLocationModel().getLat(),ChcheUtils.getInstance().getLocationModel().getLng());
            lat_end = new LatLng(Double.parseDouble(orderModel.getBegLocLat()), Double.parseDouble(orderModel.getBegLocLng()));
        }
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);
        showlines();
        initOver(ChcheUtils.getInstance().getLocationModel().getLat(),
                ChcheUtils.getInstance().getLocationModel().getLng());
    }
    private void initOver(double a, double b) {
        //定义Maker坐标点
        LatLng point = new LatLng(a, b);
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.dangqianweizhi);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
    }

    private void initErrorOver(double a, double b) {
        //定义Maker坐标点
        LatLng point = new LatLng(a, b);
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.dingweizhi);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
    }

    private void showlines() {
        // 重置浏览节点的路线数据
        route = null;
        //mBaiduMap.clear();
//        处理搜索按钮响应
//        设置起终点信息，对于tranist search 来说，城市名无意义
        PlanNode stNode = PlanNode.withLocation(lat_start);
        PlanNode enNode = PlanNode.withLocation(lat_end);
        mSearch.bikingSearch((new BikingRoutePlanOption())
                .from(stNode).to(enNode));
    }



    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
        if(bikingRouteResult.error== SearchResult.ERRORNO.RESULT_NOT_FOUND){
            LatLng ll = new LatLng(ChcheUtils.getInstance().getLocationModel().getLat(),
                    ChcheUtils.getInstance().getLocationModel().getLng());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(17.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            initErrorOver(Double.parseDouble(orderModel.getBegLocLat()), Double.parseDouble(orderModel.getBegLocLng()));
            return;
        }
        if (bikingRouteResult == null || bikingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(NoOrderMapActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
        }
        if (bikingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            // result.getSuggestAddrInfo()
            return;
        }
        if (bikingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            nodeIndex = -1;
            route = bikingRouteResult.getRouteLines().get(0);
            BikingRouteOverlay overlay = new MyBikingRouteOverlay(mBaiduMap);
            routeOverlay = overlay;
            mBaiduMap.setOnMarkerClickListener(overlay);
            overlay.setData(bikingRouteResult.getRouteLines().get(0));//设置路线数据
            overlay.addToMap();//将所有overlay添加到地图中
            overlay.zoomToSpan(); //缩放地图
        }
        MapStatus newMapStatus = new MapStatus.Builder().target(lat_current).zoom(16).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(newMapStatus);
        mBaiduMap.animateMapStatus(mMapStatusUpdate, 250);
    }
    private class MyBikingRouteOverlay extends BikingRouteOverlay {

        public MyBikingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }
        @Override
        public BitmapDescriptor getStartMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.mipmap.icon_st);
            }
            return null;
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            if (useDefaultIcon) {
                return BitmapDescriptorFactory.fromResource(R.mipmap.icon_en);
            }
            return null;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        map_view.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        map_view.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
